package com.myplans.server.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.LongConverter;
import org.apache.log4j.Logger;

import com.myplans.server.util.converter.AndroidPlanConverter;
import com.myplans.server.util.converter.CategoryConverter;
import com.myplans.server.util.converter.DateCalendarConverter;
import com.myplans.server.util.converter.PlanConverter;
import com.myplans.server.util.converter.UserConverter;
import com.myplans.shared.AndroidPlan;
import com.myplans.shared.Category;
import com.myplans.shared.Plan;
import com.myplans.shared.User;
import com.myplans.vo.CategoryValue;
import com.myplans.vo.PlanValue;
import com.myplans.vo.UserValue;

/**
 * @author Andrei Iordache
 * 
 */
public final class Util {

	private static String fileName = "application.properties";
	private static Properties properties = new Properties();
	private static Logger logger = Logger.getLogger(Util.class);
	public static String defaultImage = "" +
			"AEYAQAC/4yPqcvtD6OctNqLs968+w+G4kiW5omm6sq27gvH8kzX9o3n+s73/g8MCofEovGITCqXzKbz" +
			"CY1Kp9Sq9YrNarfcrvcLVgrG4bJxjE6r1+y1+b1ry+dzuD1Gz+vV975pDxjo5kfIIXiIKFC4OJHo+Kj" +
			"IKBkAWVk5SWip6Yh5t/mZ2PkGSnooGlaaCnjKpeoayGr1OgsbO0WLq2crldtbtwvlKzwI3DR8jFZsjM" +
			"ysLMYM7fwDTc0m7VOdnXbNo+0dyW3zPQ4eLkP+bQ6Dzq7Owg5f7k4SXz//Vx9/P5Jvvx/Sz9+/DgHzD" +
			"TRUUOBBDAkVLrTQUN9DhhHhTbxQ0eJFCv8ZNW6U0NHjxwch242EUBLdSZQpx61s0NLkywQxVc5EUNPm" +
			"TQM5dd7sSW4nT6AudxItOvNo0J9KvRlt6jQpVG1Mp0Z7arVZ1azIsHLtKvUr2JViqb0sa3Yk2rQb17K" +
			"d6LZa27hX4dLVavfusbl6h13sO3Yh4L15B/cqbDgX4sS0/jJWvPixKseSZ/GtPJky5lSXN5Pq7PnTx9" +
			"CfR5MWffK0JrKqL6VuDYk1bE6vZ4eSbVvQ2dy6w/LO4/X3L9/C5QQvbm0rcmLEl2877pyM0OjMmzsXO" +
			"pS69Onat3PXjj179PDir5PvTp4S9fTqx6cHfx4+dPPK5Vt3X3/9fPy7uyf/y68fgPTdtxx2/nlHIHIG" +
			"+hfegQ0yuCB6EdonYHEPSvhdgBMOmCGH+/32HoUf8haihh0WWKKHI9rGnogngsheewrGKKNwNNZI4o0" +
			"4sqjjjD3CqOOOrQV5AJBE5khkkbMlucCQTCqg2pNQkiZlk55VaWVlWDKA2ZZcaunllI+FmSVjZJZp2J" +
			"lipqkmTWa26SabcCo52JxxAmYnTnXmqWdffPap15903iXooHQVWp5biCa61qJCiuUoo5BGemikj2Zl6" +
			"aVWZVoppXFx+qmlnTo66qKlInpqoakKuuqfrfL5ap6x2jnrnLXCeWubuaq565m9kvlrmMF6GaqoioLa" +
			"KLJo6WWqKVTMFutpsqQSqqqctI5pa5e8hiZslFjyyCSSP9p4o4orLhmfi7ipq9aB8tTmYH/uvhuZu6D" +
			"N+9w/+K7izr63SeOvJbsEDMopBGdWyMGN+aHwYaM0LAwqEAemxcRvyWJxNlVk7NMyHHeMxMf9hCxyQk" +
			"SU3NDJKBek8sojD+FyQC3HLJEQNBsE8801B6HzzkD0LNLPQIOMzdBL2Ww0UjwnnU7OTFPl9NNyRS11X" +
			"UtXffE0WGdd9NZ4Xe01YUiHLTbYZPsy89kOj6322ma3vTDbcMf99tyupG333VTnjXDdfJcm99+lkFAAADs=";

	private Util() {
	}

	static {
		loadProperties();
		ConvertUtils.register(new UserConverter(), User.class);
		ConvertUtils.register(new UserConverter(), UserValue.class);
		ConvertUtils.register(new LongConverter(null), Long.class);
		ConvertUtils.register(new PlanConverter(), Plan.class);
		ConvertUtils.register(new PlanConverter(), PlanValue.class);
		ConvertUtils.register(new AndroidPlanConverter(), AndroidPlan.class);
		ConvertUtils.register(new AndroidPlanConverter(), PlanValue.class);
		ConvertUtils.register(new CategoryConverter(), Category.class);
		ConvertUtils.register(new CategoryConverter(), CategoryValue.class);
		ConvertUtils.register(new DateCalendarConverter(), Date.class);
		ConvertUtils.register(new DateCalendarConverter(), Calendar.class);
	}

	private static void loadProperties() {
		InputStream stream = Util.class.getClassLoader().getResourceAsStream(
				fileName);
		try {
			properties.load(stream);
		} catch (IOException e) {
		}
	}

	/**
	 * BeanRefFactoryId property for core database connecting dates
	 * 
	 * @return beanId
	 */
	public static String getBeanRefFactory() {
		return properties.getProperty("beanRefFactory");
	}

	public static String getFacebookClientId() {
		return properties.getProperty("facebook.clientId");
	}

	public static String getFacebookClientSecret() {
		return properties.getProperty("facebook.clientSecret");
	}

	public static String fetchURL(final String u) {
		String retStr = "";
		try {
			final URL url = new URL(u);
			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
	        InputStream is = url.openStream();
	        int r;
	        while ((r = is.read()) != -1) {
	            baos.write(r);
	        }
	        return new String(baos.toByteArray());

		} catch (final MalformedURLException e) {
			logger.error("MalformedURLException calling url" + e.getMessage());
		} catch (final IOException e) {
			logger.error("IOException calling url" + e.getMessage());
		}
		return retStr;
	}
	
	public static byte[] getPictureFromUrl(String u) 
	          throws IOException {
	  try {
		  final URL url = new URL(u);
			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
	        InputStream is = url.openStream();
	        int r;
	        while ((r = is.read()) != -1) {
	            baos.write(r);
	        }
	        return baos.toByteArray();
      }
      catch (MalformedURLException ex) {
        System.err.println(ex);
      } 
      catch (IOException ex) {
        System.err.println(ex);      
      }
	  return null;
	}
	   
	
	public static String encode(final String text) {
        try {
            return URLEncoder.encode(text, "UTF-8");
        } catch (final UnsupportedEncodingException e) {
            throw new IllegalStateException(e);
        }
    }

}
